package com.example.shopping_li.me;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.TextUtilsCompat;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shopping_li.R;
import com.example.shopping_li.URLUtils;
import com.example.shopping_li.utils.BaseActivity;
import com.example.shopping_li.utils.EditUserDialog;
import com.example.shopping_li.utils.SaveUserUtils;
import com.example.shopping_li.utils.UpdateHeadDialog;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
public class PersonCenterActivity extends BaseActivity {
    TextView telTv,nickTv,nameTv,addressTv;
    CircleImageView headIv;
    UserBean.DataBean bean;  //该进入时获取的用户信息
    UserBean.DataBean ub;    //修改的用户信息
    String filepath;    //图片地址
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center);
        initView();
        bean = getUserInfo();
        filepath = getCacheDir().getAbsolutePath()+ File.separator+bean.getPhone()+".png";
        setViewData(bean);   //设置显示数据
        File headfile = new File(filepath);
        if (headfile.exists()) {
//            Picasso.with(this).load(headfile).into(headIv);
            Bitmap bitmap = BitmapFactory.decodeFile(filepath);
            headIv.setImageBitmap(bitmap);
        }else{
            headIv.setImageResource(R.mipmap.icon);
        }

    }
    /* 设置显示数据*/
    private void setViewData(UserBean.DataBean bean) {
        telTv.setText(bean.getPhone());
        nickTv.setText(bean.getNickname());
        nameTv.setText(bean.getName());
        addressTv.setText(bean.getAddress());
    }
    /* 获取保存的个人数据信息*/
    private UserBean.DataBean getUserInfo() {
        UserBean.DataBean bean = SaveUserUtils.getUserinfo();
        if (bean == null) {
            bean= SaveUserUtils.getUserToObj(this);
        }
        return bean;
    }
    private void initView() {
        telTv = findViewById(R.id.center_tv_zh);
        nickTv = findViewById(R.id.center_tv_nick);
        nameTv = findViewById(R.id.center_tv_name);
        addressTv = findViewById(R.id.center_tv_address);
        headIv = findViewById(R.id.center_iv_touxiang);
    }
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.info_iv_back: //返回
                boolean flag = isSameUser();  //true
                if (flag) {  //没改
                    finish();
                } else {
                    showBackDialog();
                }
                break;
            case R.id.info_tv_save:  //保存
                //1.判断页面信息是否改变了，如果改变联网更新信息，然后更新本地信息  2.没有改变，提示用户并未改变不用联网了
                boolean isSameObj=isSameUser();
                if (isSameObj) {
                    Toast.makeText(this,"并未修改个人信息...",Toast.LENGTH_SHORT).show();
                }else{  //网络修改信息
                    postData();
                }
                break;
            case R.id.center_iv_touxiang: //头像
                selectImgDialog();
                break;
            case R.id.center_iv_edit_nick: //昵称
                String hint = "请修改贝壳昵称:";
                showEditDialog(hint,nickTv);
                break;
            case R.id.center_iv_edit_name: //姓名
                hint = "请修改收件姓名:";
                showEditDialog(hint,nameTv);
                break;
            case R.id.center_iv_edit_address: //地址
                hint = "请修改收件地址:";
                showEditDialog(hint,addressTv);
                break;
        }
    }
    /* 弹出选择对话框*/
    private void selectImgDialog() {
        UpdateHeadDialog dialog = new UpdateHeadDialog(this);
        dialog.show();
        dialog.setDialogWidth();
        dialog.setLocalImageListener(new UpdateHeadDialog.LocalImageListener() {
            @Override
            public void openLocalImage() {
                Intent intent = new Intent(PersonCenterActivity.this, LocallmageActivity.class);
//                startActivityForResult(intent, 200);
            }

            @Override
            public void openCamera() {
                filepath = getCacheDir().getAbsolutePath() + File.separator + bean.getPhone() + ".png";

                //跳转到手机的照相机页面
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 100);
            }
        });
    }
//        dialog.setLoadImageListener(new UpdateHeadDialog.LoadImageListener() {
//            @Override
//            public void openLocalImage() {
//
//            }
//
//            @Override
//            public void openCamera() {
//
//            }
//        });
//    }

    //    接受界面回传值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            Bundle bundle = data.getExtras();
            Bitmap bm = (Bitmap) bundle.get("data");
            if (bm!=null) {
                headIv.setImageBitmap(bm);
                saveFile(bm,filepath);
            }
        }else if (requestCode==200){
            String fpath = data.getStringExtra("fpath");
            if (fpath!=null) {
                Bitmap bm = BitmapFactory.decodeFile(fpath);
                headIv.setImageBitmap(bm);
                saveFile(bm,filepath);
            }
        }
    }
    /* 将位图保存到本地*/
    public void saveFile(Bitmap bm,String filepath) {
        File photoFile = new File(filepath);
        BufferedOutputStream bos = null;
        try{
            bos = new BufferedOutputStream(new FileOutputStream(photoFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        }catch(Exception e){
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();

        }finally{
            try{
                bos.flush();
                bos.close();
            }catch(Exception e){}
        }
    }

    /* 加载指定路径的图片，图片的二次采样*/
    private void loadImagPath() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bm = BitmapFactory.decodeFile(filepath, options);
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        //压缩宽和高
        int sampleWidth = outWidth/250;
        int sampleHeight = outHeight/250;
        int per = Math.max(sampleHeight,sampleWidth);
        options.inSampleSize = per;
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);
        if (bitmap!=null) {
            headIv.setImageBitmap(bitmap);
        }
    }

    private void postData() {
        Map<String,String> map = new HashMap<>();
        map.put("id",ub.getId()+"");
        map.put("address",ub.getAddress());
        map.put("nickname",ub.getNickname());
        map.put("name",ub.getName());
        postNetwork(URLUtils.updateURL,map);
    }

    /*点击了返回，但是当前数据有更新，没保存，进行的提示*/
    private void showBackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage("当前页面信息有更新，但未保存，是否仍要退出?")
                .setIcon(R.mipmap.icon)
                .setNegativeButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        postData();
                    }
                })
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PersonCenterActivity.this.finish();//当前页面关闭
                    }
                });
        builder.create().show();
    }
    /*判断当前页面是否修改内容了*/
    private boolean isSameUser() {
        boolean isSameObj;
        String nickStr = nickTv.getText().toString();
        String nameStr = nameTv.getText().toString();
        String addressStr = addressTv.getText().toString();
//              使用修改的数据，生成一个新的对象，只改变修改的部分，其他部分不变
        ub = new UserBean.DataBean(bean.getId(),bean.getPhone(),bean.getPassword(),
                nameStr,addressStr,nickStr,bean.getQuestion(),bean.getAnswer());

        isSameObj = bean.equals(ub);
        return isSameObj;
    }

    /* 点击账号的编辑图片，弹出对话框*/
    private void showEditDialog(String hint,final TextView tv) {
        final EditUserDialog dialog = new EditUserDialog(this);
        dialog.show();
        dialog.setTipHint(hint);  //设置EditText的提示信息
        dialog.setDialogWidth();   // 设置弹出窗口的大小
        dialog.setOnEnsureListener(new EditUserDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                if (!TextUtils.isEmpty(msg)) {
                    tv.setText(msg);
                }
                dialog.cancel();
            }
        });
    }
    /* 联网成功了*/
    @Override
    public void onSuccess(String result) {
        UserBean userBean = new Gson().fromJson(result, UserBean.class);
        int code = userBean.getCode();
        if (code == 200) { //成功了
            Toast.makeText(this,"更新用户信息成功！",Toast.LENGTH_SHORT).show();
            SaveUserUtils.saveUserInfo(this,ub);  //成功后将修改的对象保存到本地
            bean = ub;   //将修改后的对象赋值给之前页面的对象
        }else{
            //失败了
            Toast.makeText(this,"更新用户信息失败！",Toast.LENGTH_SHORT).show();
        }
    }
}